package com.wgz.medicalmanagement.common.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

/**
 * AI服务配置类
 * 加载AI API相关配置
 *
 * @author medical
 */
@Configuration
public class AIConfig {

    /**
     * AI API配置属性
     */
    @Bean
    @ConfigurationProperties(prefix = "ai.api")
    public AIProperties aiProperties() {
        return new AIProperties();
    }

    /**
     * RestTemplate Bean
     * 用于调用AI API，配置了超时
     *
     * @return RestTemplate实例
     */
    @Bean
    public RestTemplate aiRestTemplate() {
        // 使用SimpleClientHttpRequestFactory，不依赖HttpClient5
        org.springframework.http.client.SimpleClientHttpRequestFactory requestFactory =
                new org.springframework.http.client.SimpleClientHttpRequestFactory();

        // 设置超时
        requestFactory.setConnectTimeout(30000); // 连接超时30秒
        requestFactory.setReadTimeout(120000);   // 读取超时120秒，DeepSeek可能需要较长思考时间
        requestFactory.setBufferRequestBody(false); // 对于较大的请求体，不缓冲

        // 创建RestTemplate
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        // 配置错误处理器
        restTemplate.setErrorHandler(new org.springframework.web.client.DefaultResponseErrorHandler() {
            @Override
            public boolean hasError(org.springframework.http.client.ClientHttpResponse response) throws java.io.IOException {
                // 仅对5xx错误进行处理，让4xx错误通过以便应用层处理
                return response.getStatusCode().is5xxServerError();
            }
        });

        return restTemplate;
    }

    /**
     * 创建AI API的HTTP头

     * 
     * @param apiKey API密钥
     * @return HTTP头
     */
    public static HttpHeaders createHeaders(String apiKey) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);
        // 添加自定义请求头，提高成功率
        headers.add("User-Agent", "DeepSeek-Client/1.0.0");
        headers.add("Accept", "application/json");
        return headers;
    }
} 